package com.zhongjianjian.redisLock.service;

import com.alibaba.fastjson.JSON;
import com.zhongjianjian.redisLock.dao.StockDao;
import com.zhongjianjian.redisLock.entity.TestStock;
import com.zhongjianjian.redisLock.lock.TestLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 作者: LCG
 * 日期: 2020/2/21 20:39
 * 描述:
 */
@Component
public class TestStockService {

    @Autowired
    private StockDao stockDao;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public void getStock(Map<String,String> param){

        //获取锁
        TestLock testLock=new TestLock(redisTemplate);
        boolean lock = testLock.getLock(param.get("goodsId").toString(), param.get("userId").toString());
        if(lock){
            //查询库存
            TestStock stock = stockDao.getStock(param);

            if(stock.getStock()>=1){
                stock.setStock(stock.getStock()-1);
                //进行库存减少1操作
                int i = stockDao.updateStock(stock);
                System.out.println("------更新库存----"+i);
                //释放锁
                testLock.unLock(param.get("goodsId").toString(), param.get("userId").toString());
                testLock=null;
            }else{
                //释放锁
                testLock.unLock(param.get("goodsId").toString(), param.get("userId").toString());
                testLock=null;
                throw new RuntimeException("库存不足");
            }

        }else{
            //假如没有获取到锁，将没有获取到锁的请求加入队列，或者是定时任务，这里选择redis的消息队列
            String string = JSON.toJSONString(param);
            redisTemplate.convertAndSend("LOCK",string);
        }

    }





}
